﻿using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using TrackIT.Common.Factories;
using TrackIT.Common.Repositories;

namespace TrackIT.UnitTest.Repositories
{
    [TestClass]
    public class FileAccessRepositoryTest
    {
        [TestMethod]
        public void Load_ValidItems_ItemsLoaded()
        {
            MockWorkStreamFactory streamFactory = new MockWorkStreamFactory();
            streamFactory.TasksBuffer = HelperUtil.workListValid1;
            string rootFolder = HelperUtil.ExtractPath(Assembly.GetExecutingAssembly().Location);                
            string filename = Path.Combine(rootFolder, "FileAccessRepositoryTest_WorkLog1.txt");

            FileAccessRepository target = new FileAccessRepository(streamFactory);

            IList<string> actual = target.Load(filename).ToList();

            Assert.AreEqual(5, actual.Count);            
        }

        [TestMethod]
        public void Save_FileDoesNotAlreadyExist_NewFileCreated()
        {
            string rootFolder = HelperUtil.ExtractPath(Assembly.GetExecutingAssembly().Location);
            string filename = Path.Combine(rootFolder, "FileAccessRepositoryTest_Save_FileDoesNotAlreadyExist_NewFileCreated.txt");

            WorkStreamFactory streamFactory = new WorkStreamFactory();
            FileAccessRepository target = new FileAccessRepository(streamFactory);

            target.Save(HelperUtil.WorkListValid1, filename);

            Assert.IsTrue(File.Exists(filename));            
        }

        [TestMethod]
        [DeploymentItem("DeploymentItems\\FileAccessRepositoryTest_Save_FileAlreadyExist_ExistingFileDeletedFirst.txt")]
        public void Save_FileAlreadyExist_ExistingFileDeletedFirst()
        {
            string rootFolder = HelperUtil.ExtractPath(Assembly.GetExecutingAssembly().Location);
            string filename = Path.Combine(rootFolder, "FileAccessRepositoryTest_Save_FileAlreadyExist_ExistingFileDeletedFirst.txt");

            WorkStreamFactory streamFactory = new WorkStreamFactory();
            FileAccessRepository target = new FileAccessRepository(streamFactory);

            target.Save(HelperUtil.WorkListValid1, filename);

            Assert.IsTrue(File.Exists(filename));

            string expected = HelperUtil.StripWhiteSpace(HelperUtil.workListValid1);   
            string actual = HelperUtil.StripWhiteSpace(File.ReadAllText(filename).TrimEnd()); 
        
            Assert.AreEqual(expected, actual);
        }
    }
}
